package cn.fy.appcode;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import cn.fy.appcode.activity.NewActivity;
import cn.fy.appcode.databinding.ActivityMainBinding;
import cn.fy.appcode.notification.NotificationBroadcastReceiver;
import cn.fy.appcode.service.BindService;
import cn.fy.appcode.service.MyIntentService;
import cn.fy.appcode.service.StartService;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;


    /*** Service ***/
    private BindService bindService;
    private boolean isBind = false;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(getClass().getName(), "onServiceConnected");
            bindService = ((BindService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(getClass().getName(), "onServiceDisconnected");
            bindService = null;
        }
    };

    /*** Content Provider ***/
    private static final String TAB_NAME = "user";
    private static final String AUTHORITY = "cn.fy.provider";
    public static final Uri URI_USER_DIR = Uri.parse("content://" + AUTHORITY + "/" + TAB_NAME);
    public static final Uri URI_USER_ITEM = Uri.parse("content://" + AUTHORITY + "/" + TAB_NAME + "/1");

    // 数据库字段名
    public static final String COLUMN_ID = "ID";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_AGE = "age";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //启动新Activity，并接收返回
        binding.btnNewActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launcherNewActivity.launch(true);
            }
        });

        /*** Broadcast Receiver ***/
        Button btnNotification = binding.btnNotification;
        btnNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentClick = new Intent(MainActivity.this, NotificationBroadcastReceiver.class);
                intentClick.setAction("notification_clicked");
                intentClick.putExtra(NotificationBroadcastReceiver.TYPE, 1);
                PendingIntent pendingIntentClick = PendingIntent.getBroadcast(MainActivity.this, 0, intentClick, PendingIntent.FLAG_ONE_SHOT);

                Intent intentCancel = new Intent(MainActivity.this, NotificationBroadcastReceiver.class);
                intentCancel.setAction("notification_cancelled");
                intentCancel.putExtra(NotificationBroadcastReceiver.TYPE, 1);
                PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(MainActivity.this, 0, intentCancel, PendingIntent.FLAG_ONE_SHOT);

                Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                String CHANNEL_ID = "appcode_channel_id";
                Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
                        .setContentTitle("这是测试通知标题")  //设置标题
                        .setContentText("这是测试通知内容") //设置内容
                        .setWhen(System.currentTimeMillis())  //设置时间
                        .setSmallIcon(R.mipmap.ic_launcher)  //设置小图标
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))   //设置大图标
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntentClick)
                        .setDeleteIntent(pendingIntentCancel)
                        .setAutoCancel(true)
                        .build();
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                manager.notify(NotificationBroadcastReceiver.NOTIFICATION_ID, notification);
            }
        });

        /*** Service ***/
        Intent intentStart = new Intent(this, StartService.class);
        Button btnStartService = binding.btnStartService;
        btnStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(getClass().getName(), "onCreate1111");
                startService(intentStart);
            }
        });

        Button btnStopService = binding.btnStopService;
        btnStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(intentStart);
            }
        });

        Button btnBindService = binding.btnBindService;
        btnBindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isBind) {
                    Intent intentBind = new Intent(MainActivity.this, BindService.class);
                    bindService(intentBind, serviceConnection, Context.BIND_AUTO_CREATE);
                    isBind = true;
                }
            }
        });

        Button btnUnbindService = binding.btnUnbindService;
        btnUnbindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isBind) {
                    isBind = false;
                    unbindService(serviceConnection);
                    bindService = null;
                }
            }
        });

        Button btnIntentService = binding.btnIntentService;
        btnIntentService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(MainActivity.this, MyIntentService.class));
            }
        });

        /*** Content Provider ***/
        binding.btnAddContentUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                providerInsert();
            }
        });

        binding.btnEditContentUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                providerUpdate();
            }
        });

        binding.btnDeleteContentUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                providerDelete();
            }
        });

        binding.btnQueryContentUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                providerQuery();
            }
        });

    }

    /******Activity调用接收返回******/
    ActivityResultLauncher launcherNewActivity = registerForActivityResult(new ActivityResultContract<Boolean, String>() {
        @NonNull
        @Override
        public Intent createIntent(@NonNull Context context, Boolean input) {
            Intent intent = new Intent(MainActivity.this, NewActivity.class);
            intent.putExtra("b", input);
            return intent;
        }

        @Override
        public String parseResult(int resultCode, @Nullable Intent intent) {
            return intent.getStringExtra("resultMsg");
        }
    }, result -> Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show());

    // 通过ContentProvider插入数据
    private void providerInsert() {
        runDatabase(() -> {
            ContentValues values = new ContentValues();
            // 数据库字段名+当前字段值
            values.put(COLUMN_NAME, "Tom");
            values.put(COLUMN_AGE, 1);
            Uri insertUri = getContentResolver().insert(URI_USER_DIR, values);
            Log.d(getClass().getName(), "providerInsert:: " + insertUri);
        });
    }

    private void providerUpdate() {
        runDatabase(() -> {
            ContentValues values = new ContentValues();
            values.put(COLUMN_NAME, "Tom");
            values.put(COLUMN_AGE, 1);
            int updateId = getContentResolver().update(URI_USER_ITEM, values, null,
                    null);
            Log.d(getClass().getName(), "providerUpdate:: " + updateId);
        });
    }

    private void providerDelete() {
        runDatabase(() -> {
            int deleteId = getContentResolver().delete(URI_USER_ITEM, null, null);
            Log.d(getClass().getName(), "providerDelete:: " + deleteId);
        });
    }

    private void providerQuery() {
        runDatabase(() -> {
            Cursor cursor = getContentResolver().query(URI_USER_DIR, null, null,
                    null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    long id = cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_ID));
                    String name = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME));
                    Log.d(getClass().getName(), "providerQuery id:: " + id + " ,name:: " + name);
                }
                cursor.close();
            }
        });
    }

    private void runDatabase(Runnable target) {
        new Thread(target).start();
    }
}